package com.catt.orderdinner.controller;

import com.catt.orderdinner.common.KeyUtils;
import com.catt.orderdinner.dataobject.TbProject;
import com.catt.orderdinner.service.ProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

@Controller
@RequestMapping("/admin/project")
public class AdminProjectController {
    @Autowired
    private ProjectService projectService;

    @RequestMapping("list")
    public String getProjectList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                              @RequestParam(value = "size", defaultValue = "2") Integer size, Model model){
        PageRequest request = new PageRequest(page - 1, size);
        Page<TbProject> allProject = projectService.findAll(request);
        model.addAttribute("pageUrl","/admin/project/list");
        model.addAttribute("currentPage",page);
        model.addAttribute("pageInfo",allProject);
        model.addAttribute("size",size);
        return "project/projectList";
    }

    @GetMapping("showForm")
    public String showForm(String id, Model model){
        if (id!=null&&!id.equalsIgnoreCase("")) {
//            int shopId = Integer.parseInt(id);
            TbProject project = projectService.findOneByUserId(id);
            model.addAttribute("project",project);
        }
        return "project/projectForm";
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public String saveAndUpdate(@Valid TbProject form, Model model){
        TbProject Tproject = new TbProject();
        //如果foodId为空, 说明是新增
        if (!StringUtils.isEmpty(form.getProjectId())) {
            Tproject = projectService.findOneByUserId(form.getProjectId());
        }else {
            form.setProjectId(KeyUtils.genUniqueKey());
        }
        BeanUtils.copyProperties(form, Tproject);
        try {
            projectService.save(Tproject);
            return "操作成功";
        }catch (Exception e){
            return "操作失败";
        }
    }

    @RequestMapping("del")
    @ResponseBody
    public String del(String ids){
        try {
            String[] idss = ids.split("-");
            for(String projectId : idss){
                projectService.del(projectId);
            }
            return "success";
        }catch (Exception e){
            return "failed";
        }
    }
}
